package com.woniuxy.food.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.food.infra.mapper.*;
import com.woniuxy.food.infra.model.*;
import com.woniuxy.food.service.FoodSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.food.service.servicedto.FoodSkuServiceDto;
import com.woniuxy.food.service.serviceparam.InsertFoodSkuServiceParam;
import com.woniuxy.food.service.serviceparam.SearchFoodSkuByConditionServiceParam;
import com.woniuxy.food.service.serviceparam.UpdateFoodSkuServiceParam;
import common.WoniuPage;
import exception.MallException;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.CommonResultCodeEnum;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 菜品sku表 服务实现类
 * </p>
 *
 * @author 刘德华
 * @since 2023-07-19
 */
@Service
public class FoodSkuServiceImpl extends ServiceImpl<FoodSkuMapper, FoodSku> implements FoodSkuService {

    @Autowired
    private FoodSkuMapper foodSkuMapper;
    @Autowired
    private FoodSpuMapper foodSpuMapper;
    @Autowired
    private FoodPropMapper foodPropMapper;
    @Autowired
    private FoodPropValueMapper foodPropValueMapper;
    @Autowired
    private FoodSkuPropValueMapper foodSkuPropValueMapper;
    @Autowired
    private FoodPicMapper foodPicMapper;
    @Autowired
    private FoodSkuPicMapper foodSkuPicMapper;
    @Override
    @GlobalTransactional
    public void insertFoodSku(InsertFoodSkuServiceParam param) {
        QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
        foodSpuQueryWrapper.eq("store_id",param.getStoreId()).eq("spu_id",param.getSpuId());
        FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
        if (foodSpu==null) {
            throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodPic> foodPicQueryWrapper = new QueryWrapper<>();
        foodPicQueryWrapper.eq("store_id",param.getStoreId()).eq("food_pic_id",param.getFoodPicId());
        FoodPic foodPic = foodPicMapper.selectOne(foodPicQueryWrapper);
        if (foodPic==null) {
            throw new MallException("当前图片不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        //将属性值排序变成快速查询码
        List<Integer> ids =Arrays.asList(param.getPropValueIds());
        for (Integer id : ids) {
            FoodPropValue foodPropValue = foodPropValueMapper.selectById(id);
            if (foodPropValue==null) {
                throw new MallException("当前菜品属性值不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            FoodProp foodProp = foodPropMapper.selectById(foodPropValue.getPropId());
            if (foodProp==null) {
                throw new MallException("当前菜品属性不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            if (foodProp.getSpuId()!=param.getSpuId()) {
                throw new MallException("当前菜品spu不存在该菜品属性", CommonResultCodeEnum.INVALID_PARAM);
            }
        }
        if (ids.size()>1) {
            for(int i=0;i<ids.size()-1;i++){
                FoodPropValue foodPropValue1 = foodPropValueMapper.selectById(ids.get(i));
                FoodPropValue foodPropValue2 = foodPropValueMapper.selectById(ids.get(i+1));
                if (foodPropValue1.getPropId()==foodPropValue2.getPropId()) {
                    throw new MallException("不可以选择相同属性的属性值", CommonResultCodeEnum.INVALID_PARAM);
                }
            }
        }
        Collections.sort(ids);
        if (ids==null||ids.size()==0) {
            throw new MallException("没有选择菜品sku属性值", CommonResultCodeEnum.INVALID_PARAM);
        }
        String code="";
        for(int i=0;i<ids.size();i++){
            if(i!=(ids.size()-1)){
                code=code+ids.get(i)+"-";
            }else {
                code=code+ids.get(i);
            }
        }
        FoodSku foodSku = BeanUtil.toBean(param, FoodSku.class);
        foodSku.setMainPic(foodPic.getPicPath());
        foodSku.setDiscountPrice(BigDecimal.valueOf(0));
        foodSku.setSkuState("FORBID");
        foodSku.setSalesCount(0L);
        foodSku.setQuickQueryCode(code);
        save(foodSku);
        for (Integer id : ids) {
            FoodSkuPropValue foodSkuPropValue = new FoodSkuPropValue();
            foodSkuPropValue.setSkuId(foodSku.getSkuId());
            foodSkuPropValue.setPropValueId(id);
            foodSkuPropValueMapper.insert(foodSkuPropValue);
        }
    }

    @Override
    @GlobalTransactional
    public void updateFoodSkuStateByIds(Integer storeId,Integer[] ids,String skuState) {
        List<Integer> integers = Arrays.asList(ids);
        for (Integer id : integers) {
            FoodSku foodSku = foodSkuMapper.selectById(id);
            if (foodSku==null) {
                throw new MallException("当前菜品sku不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            if (foodSku.getSkuState().equals(skuState)) {
                throw new MallException("当前菜品sku已是当前状态", CommonResultCodeEnum.INVALID_PARAM);
            }
            QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
            foodSpuQueryWrapper.eq("store_id",storeId).eq("spu_id",foodSku.getSpuId());
            FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
            if (foodSpu==null) {
                throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            if ("NORMAL".equals(skuState)) {
                if (foodSpu.getSpuState().equals("FORBID")) {
                    throw new MallException("当前菜品spu为下架状态", CommonResultCodeEnum.INVALID_PARAM);
                }
            }

        }
        for (Integer id : integers) {
            FoodSku foodSku = foodSkuMapper.selectById(id);
            foodSku.setSkuState(skuState);
            foodSkuMapper.updateById(foodSku);
        }
    }

    @Override
    @GlobalTransactional
    public void updateFoodSku(UpdateFoodSkuServiceParam param) {
        FoodSku foodSku = foodSkuMapper.selectById(param.getSkuId());
        if (foodSku==null) {
            throw new MallException("当前菜品sku不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
        foodSpuQueryWrapper.eq("store_id",param.getStoreId()).eq("spu_id",param.getSpuId());
        FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
        if (foodSpu==null) {
            throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodPic> foodPicQueryWrapper = new QueryWrapper<>();
        foodPicQueryWrapper.eq("store_id",param.getStoreId()).eq("food_pic_id",param.getFoodPicId());
        FoodPic foodPic = foodPicMapper.selectOne(foodPicQueryWrapper);
        if (foodPic==null) {
            throw new MallException("当前图片不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        //将属性值排序变成快速查询码
        List<Integer> ids =Arrays.asList(param.getPropValueIds());
        for (Integer id : ids) {
            FoodPropValue foodPropValue = foodPropValueMapper.selectById(id);
            if (foodPropValue==null) {
                throw new MallException("当前菜品属性值不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            FoodProp foodProp = foodPropMapper.selectById(foodPropValue.getPropId());
            if (foodProp==null) {
                throw new MallException("当前菜品属性不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            if (foodProp.getSpuId()!=param.getSpuId()) {
                throw new MallException("当前菜品spu不存在该菜品属性", CommonResultCodeEnum.INVALID_PARAM);
            }
        }
        if (ids.size()>1) {
            for(int i=0;i<ids.size()-1;i++){
                FoodPropValue foodPropValue1 = foodPropValueMapper.selectById(ids.get(i));
                FoodPropValue foodPropValue2 = foodPropValueMapper.selectById(ids.get(i+1));
                if (foodPropValue1.getPropId()==foodPropValue2.getPropId()) {
                    throw new MallException("不可以选择相同属性的属性值", CommonResultCodeEnum.INVALID_PARAM);
                }
            }
        }
        Collections.sort(ids);
        if (ids==null||ids.size()==0) {
            throw new MallException("没有选择菜品sku属性值", CommonResultCodeEnum.INVALID_PARAM);
        }
        String code="";
        for(int i=0;i<ids.size();i++){
            if(i!=(ids.size()-1)){
                code=code+ids.get(i)+"-";
            }else {
                code=code+ids.get(i);
            }
        }
        QueryWrapper<FoodSkuPropValue> foodSkuPropValueQueryWrapper = new QueryWrapper<>();
        foodSkuPropValueQueryWrapper.eq("sku_id",param.getSkuId());
        List<FoodSkuPropValue> foodSkuPropValues = foodSkuPropValueMapper.selectList(foodSkuPropValueQueryWrapper);
        for (FoodSkuPropValue foodSkuPropValue : foodSkuPropValues) {
            foodSkuPropValueMapper.deleteById(foodSkuPropValue);
        }
        FoodSku foodSkuNew = BeanUtil.toBean(param, FoodSku.class);
        foodSkuNew.setMainPic(foodPic.getPicPath());
        foodSkuNew.setQuickQueryCode(code);
        foodSkuMapper.updateById(foodSkuNew);
        for (Integer id : ids) {
            FoodSkuPropValue foodSkuPropValue = new FoodSkuPropValue();
            foodSkuPropValue.setSkuId(foodSku.getSkuId());
            foodSkuPropValue.setPropValueId(id);
            foodSkuPropValueMapper.insert(foodSkuPropValue);
        }
    }

    @Override
    @GlobalTransactional
    public void updateFoodSkuSalesCount(Integer storeId,Integer skuId, Long salesCount) {
        FoodSku foodSku = foodSkuMapper.selectById(skuId);
        if (foodSku==null) {
            throw new MallException("当前菜品sku不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
        foodSpuQueryWrapper.eq("store_id",storeId).eq("spu_id",foodSku.getSpuId());
        FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
        if (foodSpu==null) {
            throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        foodSku.setSalesCount(foodSku.getSalesCount()+salesCount);
        foodSkuMapper.updateById(foodSku);
    }

    @Override
    @GlobalTransactional
    public void updateFoodSkuDiscountPrice(Integer storeId,Integer skuId, BigDecimal discountPrice) {
        FoodSku foodSku = foodSkuMapper.selectById(skuId);
        if (foodSku==null) {
            throw new MallException("当前菜品sku不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
        foodSpuQueryWrapper.eq("store_id",storeId).eq("spu_id",foodSku.getSpuId());
        FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
        if (foodSpu==null) {
            throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        foodSku.setDiscountPrice(discountPrice);
        foodSkuMapper.updateById(foodSku);
    }

    @Override
    @GlobalTransactional
    public void deleteFoodSkuByIds(Integer storeId,Integer[] ids) {
        for (Integer id : ids) {
            FoodSku foodSku = foodSkuMapper.selectById(id);
            if (foodSku==null) {
                throw new MallException("当前菜品sku不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
            QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
            foodSpuQueryWrapper.eq("store_id",storeId).eq("spu_id",foodSku.getSpuId());
            FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
            if (foodSpu==null) {
                throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
        }
        for (Integer id : ids) {
            foodSkuMapper.deleteById(id);
            QueryWrapper<FoodSkuPropValue> foodSkuPropValueQueryWrapper = new QueryWrapper<>();
            foodSkuPropValueQueryWrapper.eq("sku_id",id);
            foodSkuPropValueMapper.delete(foodSkuPropValueQueryWrapper);
            QueryWrapper<FoodSkuPic> foodSkuPicQueryWrapper = new QueryWrapper<>();
            foodSkuPicQueryWrapper.eq("sku_id",id);
            foodSkuPicMapper.delete(foodSkuPicQueryWrapper);
        }
    }

    @Override
    public WoniuPage<FoodSkuServiceDto> searchFoodSkuByCondition(SearchFoodSkuByConditionServiceParam param) {
        QueryWrapper<FoodSku> foodSkuQueryWrapper = new QueryWrapper<>();
        foodSkuQueryWrapper.eq("store_id",param.getStoreId());
        if (param.getSpuId()!=null) {
            foodSkuQueryWrapper.eq("spu_id",param.getSpuId());
        }
        if (param.getKeyword()!=null&&!"".equals(param.getKeyword())) {
            foodSkuQueryWrapper.like("sku_name",param.getKeyword());
        }
        if (param.getSkuState()!=null&&!"".equals(param.getSkuState())) {
            foodSkuQueryWrapper.eq("sku_state",param.getSkuState());
        }
        //根据前端传入字段进行排序
        if ((param.getOrder()!=null&&!"".equals(param.getOrder()))&&(param.getOrderType()!=null&&"".equals(param.getOrderType()))) {
            if (param.getOrderType().equals("升序")) {
                foodSkuQueryWrapper.orderByAsc(param.getOrder());
            }
            if (param.getOrderType().equals("降序")) {
                foodSkuQueryWrapper.orderByDesc(param.getOrder());
            }
        }
        Integer pageNum=param.getPageIndex();
        Integer pageSize=param.getPageSize();
        if (pageNum==null) {
            pageNum=1;
        }
        if (pageSize==null) {
            pageSize=5;
        }
        //设置分页查询
        Page<FoodSku> page = new Page<>(pageNum, pageSize);
        //调用分页查询方法
        foodSkuMapper.selectPage(page,foodSkuQueryWrapper);
        WoniuPage<FoodSkuServiceDto> woniuPage = new WoniuPage<>();
        woniuPage.setTotal(page.getTotal());
        woniuPage.setPages(page.getPages());
        woniuPage.setPageIndex(page.getCurrent());
        woniuPage.setPageSize(page.getSize());
        List<FoodSkuServiceDto> foodSkuServiceDtos = new ArrayList<>();
        for (FoodSku foodSku : page.getRecords()) {
            FoodSkuServiceDto foodSkuServiceDto = BeanUtil.toBean(foodSku, FoodSkuServiceDto.class);
            if (foodSku.getSkuState().equals("FORBID")) {
                foodSkuServiceDto.setSkuStateName("下架");
            }
            if (foodSku.getSkuState().equals("NORMAL")) {
                foodSkuServiceDto.setSkuStateName("上架");
            }
            FoodSpu foodSpu = foodSpuMapper.selectById(foodSkuServiceDto.getSpuId());
            foodSkuServiceDto.setSpuName(foodSpu.getSpuName());
            foodSkuServiceDtos.add(foodSkuServiceDto);
        }
        woniuPage.setList(foodSkuServiceDtos);
        return woniuPage;
    }

    @Override
    public FoodSkuServiceDto searchFoodSkuByQQC(Integer[] ids) {
        //将属性值排序变成快速查询码
        List<Integer> idList =Arrays.asList(ids);
        for (Integer id : idList) {
            FoodPropValue foodPropValue = foodPropValueMapper.selectById(id);
            if (foodPropValue==null) {
                throw new MallException("当前菜品属性值不存在", CommonResultCodeEnum.INVALID_PARAM);
            }
        }
        Collections.sort(idList);
        String code="";
        for(int i=0;i<idList.size();i++){
            if(i!=(idList.size()-1)){
                code=code+idList.get(i)+"-";
            }else {
                code=code+idList.get(i);
            }
        }
        QueryWrapper<FoodSku> foodSkuQueryWrapper = new QueryWrapper<>();
        foodSkuQueryWrapper.eq("quick_query_code",code);
        FoodSku foodSku = foodSkuMapper.selectOne(foodSkuQueryWrapper);
        FoodSkuServiceDto foodSkuServiceDto = BeanUtil.toBean(foodSku, FoodSkuServiceDto.class);
        if (foodSku.getSkuState().equals("FOEBID")) {
            foodSkuServiceDto.setSkuStateName("下架");
        }
        if (foodSku.getSkuState().equals("NORMAL")) {
            foodSkuServiceDto.setSkuStateName("上架");
        }
        FoodSpu foodSpu = foodSpuMapper.selectById(foodSkuServiceDto.getSpuId());
        foodSkuServiceDto.setSkuName(foodSpu.getSpuName());
        return foodSkuServiceDto;
    }

    @Override
    public FoodSkuServiceDto searchFoodSkuById(Integer skuId) {
        FoodSku foodSku = foodSkuMapper.selectById(skuId);
        if (foodSku==null) {
            throw new MallException("当前菜品sku不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        FoodSkuServiceDto foodSkuServiceDto = BeanUtil.toBean(foodSku, FoodSkuServiceDto.class);
        return foodSkuServiceDto;
    }

    @Override
    public List<FoodSkuServiceDto> searchFoodSkuBySpuId(Integer storeId, Integer spuId) {
        QueryWrapper<FoodSpu> foodSpuQueryWrapper = new QueryWrapper<>();
        foodSpuQueryWrapper.eq("store_id",storeId).eq("spu_id",spuId);
        FoodSpu foodSpu = foodSpuMapper.selectOne(foodSpuQueryWrapper);
        if (foodSpu==null) {
            throw new MallException("当前菜品spu不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodSku> foodSkuQueryWrapper = new QueryWrapper<>();
        foodSkuQueryWrapper.eq("spu_id",spuId);
        List<FoodSku> foodSkus = foodSkuMapper.selectList(foodSkuQueryWrapper);
        List<FoodSkuServiceDto> foodSkuServiceDtos = BeanUtil.copyToList(foodSkus, FoodSkuServiceDto.class);
        return foodSkuServiceDtos;
    }
}
